package com.goscom.app.deeset;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.goscom.app.database.DBAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class Upload extends Activity {

	private String strMerId = "";
	private DBAdapter mDB;
	private ImageView imageCapture1;
	private ImageView imageCapture2;
	private ImageView imageCapture3;
	private ImageView imageCapture4;
	private String strPath1 = "";
	private String strPath2 = "";
	private String strPath3 = "";
	private String strPath4 = "";
	private String strPathThumsnail1 = "";
	private String strPathThumsnail2 = "";
	private String strPathThumsnail3 = "";
	private String strPathThumsnail4 = "";
	private String strUpload1 = "0";
	private String strUpload2 = "0";
	private String strUpload3 = "0";
	private String strUpload4 = "0";
	private static final int CAMERA_PIC_REQUEST1 = 1000;
	private static final int CAMERA_PIC_REQUEST2 = 2000;
	private static final int CAMERA_PIC_REQUEST3 = 3000;
	private static final int CAMERA_PIC_REQUEST4 = 4000;
	private static final int GALLERY_PIC_REQUEST1 = 5000;
	private static final int GALLERY_PIC_REQUEST2 = 6000;
	private static final int GALLERY_PIC_REQUEST3 = 7000;
	private static final int GALLERY_PIC_REQUEST4 = 8000;
	private boolean mBlnCamera1 = false;
	private boolean mBlnCamera2 = false;
	private boolean mBlnCamera3 = false;
	private boolean mBlnCamera4 = false;
	private boolean mBlnResizePhoto1 = true;
	private boolean mBlnResizePhoto2 = true;
	private boolean mBlnResizePhoto3 = true;
	private boolean mBlnResizePhoto4 = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upload);

		imageCapture1 = (ImageView) findViewById(R.id.imgUploadCapture1);
		imageCapture2 = (ImageView) findViewById(R.id.imgUploadCapture2);
		imageCapture3 = (ImageView) findViewById(R.id.imgUploadCapture3);
		imageCapture4 = (ImageView) findViewById(R.id.imgUploadCapture4);

		mDB = new DBAdapter(Upload.this);

		getMerId();
	}

	public void getMerId() {
		try {
			strMerId = getIntent().getStringExtra("merid");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (strMerId != null) {
			mDB.open();
			ContentValues content = new ContentValues();
			content = mDB.queryDataByMerId("UPLOAD", strMerId);
			if (content != null) {
				strPathThumsnail1 = content.getAsString("name1");
				if (strPathThumsnail1.equals("") == false) {
					mBlnResizePhoto1 = false;
					strUpload1 = content.getAsString("upload1");
					strPath1 = content.getAsString("image1");
					imageCapture1.setImageBitmap(BitmapFactory
							.decodeFile(content.getAsString("name1")));

					imageCapture1.setVisibility(View.VISIBLE);
				}
				strPathThumsnail2 = content.getAsString("name2");
				if (strPathThumsnail2.equals("") == false) {
					mBlnResizePhoto2 = false;
					strUpload2 = content.getAsString("upload2");
					strPath2 = content.getAsString("image2");
					imageCapture2.setImageBitmap(BitmapFactory
							.decodeFile(content.getAsString("name2")));
					imageCapture2.setVisibility(View.VISIBLE);
				}
				strPathThumsnail3 = content.getAsString("name3");
				if (strPathThumsnail3.equals("") == false) {
					mBlnResizePhoto3 = false;
					strUpload3 = content.getAsString("upload3");
					strPath3 = content.getAsString("image3");
					imageCapture3.setImageBitmap(BitmapFactory
							.decodeFile(content.getAsString("name3")));
					imageCapture3.setVisibility(View.VISIBLE);
				}
				strPathThumsnail4 = content.getAsString("name4");
				if (strPathThumsnail4.equals("") == false) {
					mBlnResizePhoto4 = false;
					strUpload4 = content.getAsString("upload4");
					strPath4 = content.getAsString("image4");
					imageCapture4.setImageBitmap(BitmapFactory
							.decodeFile(content.getAsString("name4")));
					imageCapture4.setVisibility(View.VISIBLE);
				}
				Log.i("Upload", strUpload1 + " - " + strUpload2 + " - "
						+ strUpload3 + " - " + strUpload4);
			}
			if (mDB != null) {
				mDB.close();
			}
		}
	}

	private File getTempFile(int intOrder) {
		File fileParent = new File(Environment.getExternalStorageDirectory()
				+ File.separator + "DCMI");
		if (!fileParent.exists()) {
			fileParent.mkdir();
		}
		fileParent = new File(fileParent, "Camera");
		if (!fileParent.exists()) {
			fileParent.mkdir();
		}
		if (intOrder == 1) {
			strPath1 = fileParent.getPath() + File.separator + strMerId
					+ "-colleague1.jpg";
		}
		if (intOrder == 2) {
			strPath2 = fileParent.getPath() + File.separator + strMerId
					+ "-colleague2.jpg";
		}
		if (intOrder == 3) {
			strPath3 = fileParent.getPath() + File.separator + strMerId
					+ "-colleague3.jpg";
		}
		if (intOrder == 4) {
			strPath4 = fileParent.getPath() + File.separator + strMerId
					+ "-colleague4.jpg";
		}
		return new File(fileParent, strMerId + "-colleague" + intOrder + ".jpg");
	}

	private void showPopUpTakePhoto(final int intOrder) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("Colleague " + intOrder);
		dialog.setMessage("Please choose photo from resource!");
		dialog.setPositiveButton("Camera",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Intent intent = new Intent(
								android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
						switch (intOrder) {
						case 1:
							intent.putExtra(MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(getTempFile(1)));
							startActivityForResult(intent, CAMERA_PIC_REQUEST1);
							break;
						case 2:
							intent.putExtra(MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(getTempFile(2)));
							startActivityForResult(intent, CAMERA_PIC_REQUEST2);
							break;
						case 3:
							intent.putExtra(MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(getTempFile(3)));
							startActivityForResult(intent, CAMERA_PIC_REQUEST3);
							break;
						case 4:
							intent.putExtra(MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(getTempFile(4)));
							startActivityForResult(intent, CAMERA_PIC_REQUEST4);
							break;
						default:
							break;
						}
					}
				});
		dialog.setNegativeButton("Gallery",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Intent intent = new Intent(
								Intent.ACTION_PICK,
								android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						switch (intOrder) {
						case 1:
							startActivityForResult(intent, GALLERY_PIC_REQUEST1);
							break;
						case 2:
							startActivityForResult(intent, GALLERY_PIC_REQUEST2);
							break;
						case 3:
							startActivityForResult(intent, GALLERY_PIC_REQUEST3);
							break;
						case 4:
							startActivityForResult(intent, GALLERY_PIC_REQUEST4);
							break;
						default:
							break;
						}
					}
				});
		dialog.setNeutralButton("Close", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	public void Capture1(View v) {
		showPopUpTakePhoto(1);
	}

	public void Capture2(View v) {
		showPopUpTakePhoto(2);
	}

	public void Capture3(View v) {
		showPopUpTakePhoto(3);
	}

	public void Capture4(View v) {
		showPopUpTakePhoto(4);
	}

	private void resizePhotoGallery(String strPath, int intOrder) {
		if (strPath.equals("") == false) {
			File file = new File(strPath);
			String strResult;
			if (file.length() > 400000) {
				do {
					strResult = resizePhoto(strPath, intOrder, 30);
				} while (strResult.equals("") == true);
			} else {
				do {
					strResult = resizePhoto(strPath, intOrder, 100);
				} while (strResult.equals("") == true);
			}
		}
	}

	private void resizeAllPhoto() {
		if (mBlnResizePhoto1) {
			if (mBlnCamera1) {
				resizePhoto(strPath1, 1, 30);
			} else {
				resizePhotoGallery(strPath1, 1);
			}
			mBlnResizePhoto1 = false;
		}

		if (mBlnResizePhoto2) {
			if (mBlnCamera2) {
				resizePhoto(strPath2, 2, 30);
			} else {
				resizePhotoGallery(strPath2, 2);
			}
			mBlnResizePhoto2 = false;
		}

		if (mBlnResizePhoto3) {
			if (mBlnCamera3) {
				resizePhoto(strPath3, 3, 30);
			} else {
				resizePhotoGallery(strPath3, 3);
			}
			mBlnResizePhoto3 = false;
		}

		if (mBlnResizePhoto4) {
			if (mBlnCamera4) {
				resizePhoto(strPath4, 4, 30);
			} else {
				resizePhotoGallery(strPath4, 4);
			}
			mBlnResizePhoto4 = false;
		}
	}

	public void Logout(View v) {
		saveDB();
		resizeAllPhoto();
		startActivity(new Intent(Upload.this, Login.class));
	}

	public void goPrevious(View v) {
		saveDB();
		resizeAllPhoto();
		startActivity(new Intent(Upload.this, BankDetails.class).putExtra(
				"merid", strMerId));
	}

	public void goNext(View v) {
		saveDB();
		resizeAllPhoto();
		startActivity(new Intent(Upload.this, OfferLetter.class).putExtra(
				"merid", strMerId));
	}

	private String resizePhoto(String strPath, int intOrder, int intCompress) {
		if (strPath.equals("") == false) {
			File file = new File(strPath);
			if (file.exists()) {
				Bitmap bitmap = BitmapFactory.decodeFile(strPath);
				ByteArrayOutputStream bytes = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, intCompress, bytes);

				File filePathParent = new File(
						Environment.getExternalStorageDirectory()
								+ File.separator + "DCMI");
				if (!filePathParent.exists()) {
					filePathParent.mkdir();
				}
				filePathParent = new File(filePathParent, "Camera");
				if (!filePathParent.exists()) {
					filePathParent.mkdir();
				}
				String strPathPhoto = filePathParent.getPath() + File.separator + strMerId
						+ "-colleague" + intOrder + ".jpg";

				File filePhoto = new File(strPathPhoto);
				try {
					filePhoto.createNewFile();
					FileOutputStream fo = new FileOutputStream(filePhoto);
					fo.write(bytes.toByteArray());
					fo.close();
					return strPathPhoto;
				} catch (IOException e) {
					e.printStackTrace();
					return "";
				}
			}
		}
		return "";
	}

	public void saveDB() {
		mDB.open();
		if (mDB.queryMerchandiser("UPLOAD", strMerId) == 0) {
			insertDB();
		} else {
			mDB.deleteData("UPLOAD", strMerId);
			insertDB();
		}
		if (mDB != null) {
			mDB.close();
		}
	}

	public void insertDB() {
		Log.i("Upload", strUpload1 + " - " + strUpload2 + " - " + strUpload3
				+ " - " + strUpload4);
		ContentValues content = new ContentValues();
		content.put("merid", strMerId);
		content.put("name1", strPathThumsnail1);
		content.put("image1", strPath1);
		content.put("upload1", strUpload1);
		content.put("name2", strPathThumsnail2);
		content.put("image2", strPath2);
		content.put("upload2", strUpload2);
		content.put("name3", strPathThumsnail3);
		content.put("image3", strPath3);
		content.put("upload3", strUpload3);
		content.put("name4", strPathThumsnail4);
		content.put("image4", strPath4);
		content.put("upload4", strUpload4);
		mDB.insertData("UPLOAD", content);
	}

	// public byte[] convertToByte(String strPath) {
	// byte[] image = null;
	// if (strPath.equals("") == false) {
	// FileInputStream fileInStream;
	// try {
	// fileInStream = new FileInputStream(strPath);
	// BufferedInputStream bufInStream = new BufferedInputStream(
	// fileInStream);
	// image = new byte[bufInStream.available()];
	// bufInStream.read(image);
	// } catch (FileNotFoundException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	// return image;
	// }
	//
	// private String getRealPathFromURI(Uri contentUri) {
	// String[] proj = { MediaStore.Images.Media.DATA };
	// CursorLoader loader = new CursorLoader(this, contentUri, proj, null,
	// null, null);
	// Cursor cursor = loader.loadInBackground();
	// int column_index = cursor
	// .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	// cursor.moveToFirst();
	// return cursor.getString(column_index);
	// }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAMERA_PIC_REQUEST1) {
			if (null != data && resultCode == RESULT_OK) {
				mBlnCamera1 = true;
				mBlnResizePhoto1 = true;
				strUpload1 = "0";

				strPathThumsnail1 = saveImage(strPath1, 1);
				Log.i("thumbnail 1", strPathThumsnail1);

				imageCapture1.setImageBitmap(BitmapFactory
						.decodeFile(strPathThumsnail1));
				imageCapture1.setVisibility(View.VISIBLE);
			} else {
				Toast.makeText(this, "Please capture a image",
						Toast.LENGTH_SHORT).show();
			}
		}
		if (requestCode == CAMERA_PIC_REQUEST2) {
			if (null != data && resultCode == RESULT_OK) {
				mBlnCamera2 = true;
				mBlnResizePhoto2 = true;
				strUpload2 = "0";

				strPathThumsnail2 = saveImage(strPath2, 2);
				Log.i("thumbnail 2", strPathThumsnail2);

				imageCapture2.setImageBitmap(BitmapFactory
						.decodeFile(strPathThumsnail2));
				imageCapture2.setVisibility(View.VISIBLE);
			} else {
				Toast.makeText(this, "Please capture a image",
						Toast.LENGTH_SHORT).show();
			}
		}
		if (requestCode == CAMERA_PIC_REQUEST3) {
			if (null != data && resultCode == RESULT_OK) {
				mBlnCamera3 = true;
				mBlnResizePhoto3 = true;
				strUpload3 = "0";

				strPathThumsnail3 = saveImage(strPath3, 3);
				Log.i("thumbnail 3", strPathThumsnail3);

				imageCapture3.setImageBitmap(BitmapFactory
						.decodeFile(strPathThumsnail3));
				imageCapture3.setVisibility(View.VISIBLE);
			} else {
				Toast.makeText(this, "Please capture a image",
						Toast.LENGTH_SHORT).show();
			}
		}
		if (requestCode == CAMERA_PIC_REQUEST4) {
			if (null != data && resultCode == RESULT_OK) {
				mBlnCamera4 = true;
				mBlnResizePhoto4 = true;
				strUpload4 = "0";

				strPathThumsnail4 = saveImage(strPath4, 4);
				Log.i("thumbnail 4", strPathThumsnail4);

				imageCapture4.setImageBitmap(BitmapFactory
						.decodeFile(strPathThumsnail4));
				imageCapture4.setVisibility(View.VISIBLE);
			} else {
				Toast.makeText(this, "Please capture a image",
						Toast.LENGTH_SHORT).show();
			}
		}
		if (requestCode == GALLERY_PIC_REQUEST1) {
			if (null != data && resultCode == RESULT_OK) {
				mBlnCamera1 = false;
				mBlnResizePhoto1 = true;
				strUpload1 = "0";

				strPath1 = getPathPurePhoto(data);
				Log.i("path 1", strPath1);

				strPathThumsnail1 = saveImage(strPath1, 1);
				Log.i("thumbnail 1", strPathThumsnail1);

				imageCapture1.setImageBitmap(BitmapFactory
						.decodeFile(strPathThumsnail1));
				imageCapture1.setVisibility(View.VISIBLE);
			} else {
				Toast.makeText(this, "Please capture a image",
						Toast.LENGTH_SHORT).show();
			}
		}
		if (requestCode == GALLERY_PIC_REQUEST2) {
			if (null != data && resultCode == RESULT_OK) {
				mBlnCamera2 = false;
				mBlnResizePhoto2 = true;
				strUpload2 = "0";

				strPath2 = getPathPurePhoto(data);
				Log.i("path 2", strPath2);

				strPathThumsnail2 = saveImage(strPath2, 2);
				Log.i("thumbnail 2", strPathThumsnail2);

				imageCapture2.setImageBitmap(BitmapFactory
						.decodeFile(strPathThumsnail2));
				imageCapture2.setVisibility(View.VISIBLE);
			} else {
				Toast.makeText(this, "Please capture a image",
						Toast.LENGTH_SHORT).show();
			}
		}
		if (requestCode == GALLERY_PIC_REQUEST3) {
			if (null != data && resultCode == RESULT_OK) {
				mBlnCamera3 = false;
				mBlnResizePhoto3 = true;
				strUpload3 = "0";

				strPath3 = getPathPurePhoto(data);
				Log.i("path 3", strPath3);

				strPathThumsnail3 = saveImage(strPath3, 3);
				Log.i("thumbnail 3", strPathThumsnail3);

				imageCapture3.setImageBitmap(BitmapFactory
						.decodeFile(strPathThumsnail3));
				imageCapture3.setVisibility(View.VISIBLE);
			} else {
				Toast.makeText(this, "Please capture a image",
						Toast.LENGTH_SHORT).show();
			}
		}
		if (requestCode == GALLERY_PIC_REQUEST4) {
			if (null != data && resultCode == RESULT_OK) {
				mBlnCamera4 = false;
				mBlnResizePhoto4 = true;
				strUpload4 = "0";

				strPath4 = getPathPurePhoto(data);
				Log.i("path 4", strPath4);

				strPathThumsnail4 = saveImage(strPath4, 4);
				Log.i("thumbnail 4", strPathThumsnail4);

				imageCapture4.setImageBitmap(BitmapFactory
						.decodeFile(strPathThumsnail4));
				imageCapture4.setVisibility(View.VISIBLE);
			} else {
				Toast.makeText(this, "Please capture a image",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	public int getWidthWindow() {
		int width = 0;
		if (Build.VERSION.SDK_INT > 12) {
			DisplayMetrics metrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(metrics);
			width = metrics.widthPixels;
		} else {
			width = getWindowManager().getDefaultDisplay().getWidth(); // deprecated
		}
		return width;
	}

	public Bitmap getResizedBitmap(Bitmap bm) {
		int width = bm.getWidth();
		int height = bm.getHeight();
		int intRatio = 1;

		int intWidthWindow = getWidthWindow();

		if (width > intWidthWindow) {
			while (width / intRatio > (intWidthWindow / 2)) {
				intRatio++;
			}
		}

		float scaleWidth = ((float) width / intRatio) / width;
		float scaleHeight = ((float) height / intRatio) / height;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
				matrix, false);

		return resizedBitmap;
	}

	private String getPathPurePhoto(Intent data) {
		Uri selectedImage = data.getData();
		String[] filePathColumn = { MediaStore.Images.Media.DATA };
		Cursor cursor = getContentResolver().query(selectedImage,
				filePathColumn, null, null, null);
		cursor.moveToFirst();
		int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		String strPath = cursor.getString(columnIndex);
		cursor.close();
		return strPath;
	}

	private String saveImage(String strPath, int intOrder) {
		Bitmap thumbnail = getResizedBitmap(BitmapFactory.decodeFile(strPath));
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		thumbnail.compress(Bitmap.CompressFormat.JPEG, 80, bytes);

		File fileParent = new File(Environment.getExternalStorageDirectory()
				+ File.separator + "DCMI");
		if (!fileParent.exists()) {
			fileParent.mkdir();
		}
		fileParent = new File(fileParent, "Thumbsnail");
		if (!fileParent.exists()) {
			fileParent.mkdir();
		}
		String strPathThumbsnail = fileParent.getPath() + File.separator
				+ strMerId + "-colleague" + intOrder + ".jpg";

		File fileThumbsnail = new File(strPathThumbsnail);
		try {
			fileThumbsnail.createNewFile();
			FileOutputStream fo = new FileOutputStream(fileThumbsnail);
			fo.write(bytes.toByteArray());
			fo.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return strPathThumbsnail;
	}

	@Override
	protected void onDestroy() {
		if (mDB != null) {
			mDB.close();
		}
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		mDB.open();
		super.onResume();
	}

}
